<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/11/25 0025
 * Time: 9:19
 */
namespace app\adminapi\controller;

use app\adminapi\model\Api;
use app\api\model\JWT;
use app\api\controller\Jwt as Jwts;
use think\App;
use think\Controller;
use think\helper\Hash;
use think\Db;
use think\Session;
use app\adminapi\model\User as UserModels;
/**
 * @title 我的
 * @description 接口说明
 */
class Login extends Api
{
    /**
     * @title 后台登陆
     * @description 接口说明
     * @author 开发者
     * @url /adminapi/Login/login
     * @method POST  
     * @param name:mobile type:string require:1 default: other: desc:账号
     * @param name:password type:string require:1 default: other: desc:密码
     * @param name:code type:string require:1 default: other: desc:验证码
     * 
     */
    public function login(){
     $mobile = input('mobile');
     $password = input('password');
     $code = input('code');
     $code = trim($code);
     
     // if (!$code) {
     //     return $this->ajaxReturn(1,'验证码不能为空');
     // }
     // //验证码验证
     // $msg_code = sys_check_code($code);
     // if (!$msg_code) {
     //     return $this->ajaxReturn(1,'验证码输入错误');
     // }
     if (!$mobile) {
         return $this->ajaxReturn(1,'请输入账号');
     }
     if (!$password) {
         return $this->ajaxReturn(1,'请输入密码');
     }
    $url="http://huoban-api.luxiaoyi.vip/1.0/manage/login";
    // 传参，以数组方式
    $params = ["username"=>$mobile, "password"=>$password,];
    $header = array(
        'Accept: application/json',
     );
    $jsonStr = json_encode($params,true);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
    $output = curl_exec($ch);
    curl_close($ch);
    if(!$output){
        return $this->ajaxReturn(1,'请求错误');
    }
    $json = json_decode($output,true);

    if($json['code'] == 200){
        $where[] = ['mobile','=',$mobile];
        $info = db::name('user')->where($where)->
        field('id,hid,username,last_login_time,avatar,mobile,role,status,num,hotel,sex,position')->find();
        if(!$info){
            $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
            $randStr = str_shuffle($str);//打乱字符串
            $strs = str_shuffle('012345679');
            $rands= substr($randStr,0,6);//substr(string,start,length);返回字符串的一部分
            // print_r($json);die;
            $data['pid'] = 0;
            $data['name'] = '超级管理员';
            $data['description'] = '超级管理员';
            $data['menu_auth'] = '';
            $data['sort'] = 0;
            $data['create_time'] = time();
            $data['status'] = 1;
            $data['access'] = 1;
            $data['hid'] = substr($strs,0,9);
            $data['accessa'] = 1;
            $data['default_module'] = 1;
            $role = db::name('admin_role')->insertGetId($data);

            $res['num'] = $rands;
            $res['username'] = $json['datas']['name'];
            $res['avatar'] = '';
            $res['mobile'] = $mobile;
            $passwords =  $this->setPasswordAttr($password);
            $res['password'] = $passwords;
            $res['role'] = $role;
            $res['addtime'] = time();
            $res['hid'] = $data['hid'];
            $res['hotel'] = $json['datas']['name'];
            $res['status'] = 1;
            $res['mobiles'] = $mobile;
            $uid = db::name('user')->insertGetId($res);
            
        }else{
            $uid = $info['id'];
        }
        $UserModels = new UserModels();
        $res = $UserModels->logins($mobile,$password);
        if($res == 1){
            return $this->ajaxReturn(1,'用户不存在或被禁用！');die;
        }elseif($res == 2){
            return $this->ajaxReturn(1,'禁止访问，原因：未分配角色！');die;
        }elseif($res == 3){
            return $this->ajaxReturn(1,'禁止访问，用户所在角色未启用或禁止访问后台！');die;
        }elseif($res == 4){
            return $this->ajaxReturn(1,'账号或者密码错误！');die;
        }elseif($res == 5){
            return $this->ajaxReturn(1,'登录信息更新失败，请重新登录！');die;
        }elseif($res == 6){
            return $this->ajaxReturn(1,'未分配任何节点权限！');die;
        }elseif($res == 7){
            $payload=array('iss'=>'admin','iat'=>time(),'exp'=>time()+7200,'nbf'=>time(),'sub'=>'www.admin.com','jti'=>md5(uniqid('JWT').time()),'uid'=>$info['id']);
            $jwt = new Jwts();
            $token = $jwt->getToken($payload);
            $user_token = db('user_member')->where('uid',$info['id'])->where('type',2)->value('flag');
            if($user_token){
                if($user_token != $token){
                    db::name('user_member')->where('flag',$user_token)->where('type',2)->update(['flag'=>$token]);
                }
            }else{
                $re['uid'] = $uid;
                $re['flag'] = $token;
                $re['addtime'] = time();
                $re['type'] = 2;
                db::name('user_member')->insert($re);
            }
            $info = db::name('user')->where('id',$uid)->
            field('id,hid,username,last_login_time,avatar,mobile,role,status,num,hotel,sex,position')->find();
            $info['token'] = $token;
            // $getPayload_test = $jwt->verifyToken($token_test);
            return $this->ajaxReturn(0,'成功',$info);
        }
    }
    if($json['code'] != 200){
        $info = db::name('user')->where('mobile',$mobile)->find();
        if($info){
            if(!Hash::check((string)$password, $info['password'])){
                return $this->ajaxReturn(1,'账号密码错误');
            }else{
                if($info){
                    $payload=array('iss'=>'admin','iat'=>time(),'exp'=>time()+7200,'nbf'=>time(),'sub'=>'www.admin.com','jti'=>md5(uniqid('JWT').time()),'uid'=>$info['id']);
                    $jwt = new Jwts();
                    $token = $jwt->getToken($payload);
                    $user_token = db('user_member')->where('uid',$info['id'])->where('type',2)->value('flag');
                    if($user_token){
                        if($user_token != $token){
                            db::name('user_member')->where('flag',$user_token)->where('type',2)->update(['flag'=>$token]);
                        }
                    }else{
                        $re['uid'] = $info['id'];
                        $re['flag'] = $token;
                        $re['addtime'] = time();
                        $re['type'] = 2;
                        db::name('user_member')->insert($re);
                    }
                    $info['token'] = $token;
                    // $getPayload_test = $jwt->verifyToken($token_test);
                    return $this->ajaxReturn(0,'成功',$info);
                }
            }
            return $this->ajaxReturn(1,'账号密码错误');
        }
    }

 }
 // 对密码进行加密
 public function setPasswordAttr($value)
 {
      return Hash::make((string)$value);
 }
 public function curl_get($url)
{

	$info = curl_init();
	curl_setopt($info,CURLOPT_RETURNTRANSFER,true);
	curl_setopt($info,CURLOPT_HEADER,0);
	curl_setopt($info,CURLOPT_NOBODY,0);
	curl_setopt($info,CURLOPT_SSL_VERIFYPEER,false);
	curl_setopt($info,CURLOPT_SSL_VERIFYPEER,false);
	curl_setopt($info,CURLOPT_SSL_VERIFYHOST,false);
	curl_setopt($info,CURLOPT_URL,$url);
	$output = curl_exec($info);
	curl_close($info);
	return $output;
}

}